package com.edie.customview.modular;

import android.Manifest;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v4.os.CancellationSignal;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.edie.customview.R;
import com.edie.customview.helper.CryptoObjectHelper;
import com.edie.customview.data.entity.ContactEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.crypto.Cipher;

/**
 * - @Description:  主页
 * - @Author:  edie
 * - @Time:  2018/6/15 上午11:13
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private FingerprintManagerCompat mFingerprintManager;
    private FingerprintManagerCompat.AuthenticationCallback mCallback;
    private CancellationSignal mSignal;

    public static void start(Context context) {
        context.startActivity(new Intent(context, MainActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.contact).setOnClickListener(this);
        findViewById(R.id.test2).setOnClickListener(this);
        findViewById(R.id.fingerprint_btn).setOnClickListener(this);

        mFingerprintManager = FingerprintManagerCompat.from(this);
        mSignal = new CancellationSignal();
        mCallback = new FingerprintManagerCompat.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errMsgId, CharSequence errString) {
                super.onAuthenticationError(errMsgId, errString);
                Log.i(TAG, "onAuthenticationError: errMsgId = " + errMsgId + ", errString = " + errString);
            }

            @Override
            public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
                super.onAuthenticationHelp(helpMsgId, helpString);
                Log.i(TAG, "onAuthenticationHelp: helpMsgId = " + helpMsgId + ", helpString = " + helpString);
            }

            @Override
            public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                FingerprintManagerCompat.CryptoObject object = result.getCryptoObject();
                if (object != null) {
                    Cipher cipher = object.getCipher();
//                    try {
                    //doFinal (**) 这里是解密保存的加密串
//                        byte[] bytes = cipher.doFinal();
//                        Log.i(TAG, "onAuthenticationSucceeded: " + bytes);
//                    } catch (IllegalBlockSizeException e) {
//                        e.printStackTrace();
//                    } catch (BadPaddingException e) {
//                        e.printStackTrace();
//                    }
                    Log.i(TAG, "onAuthenticationSucceeded: \n Cipher = " + cipher + "\nMac = " + object.getMac() + "\nSignature = " + object.getSignature());
                }
                Log.i(TAG, "onAuthenticationSucceeded: ");
            }

            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
                Log.i(TAG, "onAuthenticationFailed: 失败");
            }
        };

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onStart() {
        super.onStart();
        if (mFingerprintManager.isHardwareDetected()) {
            KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            if (keyguardManager.isKeyguardSecure() && mFingerprintManager.hasEnrolledFingerprints()) {
                //设置了安全保护  有指纹密码
                // this device is secure.
                mSignal = new CancellationSignal();
//                mFingerprintManager.authenticate(null, 0, mSignal, mCallback, null);
                try {
                    CryptoObjectHelper objectHelper = new CryptoObjectHelper();
                    mFingerprintManager.authenticate(objectHelper.buildCryptoObject(), 0, mSignal, mCallback, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (mFingerprintManager.hasEnrolledFingerprints()) {
                }
            } else {
                //提示开启系统指纹锁
                new AlertDialog.Builder(this)
                        .setMessage("请先到手机系统设置中添加指纹")
                        .show();
            }
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mSignal != null) {
            mSignal.cancel();
            mSignal = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.contact:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
                } else {
                    //有权限时,调用自定义函数，读取系统联系人
                    readContacts();
                }

                break;
            case R.id.test2:
                String[] contacts = getContacts();
                List<String> strings = Arrays.asList(contacts);

                Log.i(TAG, "onClick: \n" + strings);

                break;
            case R.id.fingerprint_btn:
                //指纹识别
                boolean hardwareDetected = mFingerprintManager.isHardwareDetected();
                Log.i(TAG, "onClick: 指纹识别 = " + hardwareDetected);
                break;
        }
    }

    private void readContacts() {
        ArrayList<ContactEntity> list = new ArrayList<>();
        Cursor cursor = null;
        try {
            //cursor指针 query询问 contract协议 kinds种类
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    list.add(new ContactEntity(displayName, number));
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        JSONArray jsonArray = new JSONArray();
        try {
            JSONObject jsonObject;
            for (ContactEntity entity : list) {
                jsonObject = new JSONObject();

                jsonObject.put("name", entity.name);
                jsonObject.put("phone", entity.phone);
                jsonArray.put(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "readContacts: " + jsonArray.toString());
        Log.i(TAG, "readContacts: " + list);
    }

    private String[] getContacts() {
        //联系人的Uri，也就是content://com.android.contacts/contacts
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        //指定获取_id和display_name两列数据，display_name即为姓名
        String[] projection = new String[]{
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME
        };
        //根据Uri查询相应的ContentProvider，cursor为获取到的数据集
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        String[] arr = new String[cursor.getCount()];
        int i = 0;
        if (cursor != null && cursor.moveToFirst()) {
            do {
                Long id = cursor.getLong(0);
                //获取姓名
                String name = cursor.getString(1);
                //指定获取NUMBER这一列数据
                String[] phoneProjection = new String[]{
                        ContactsContract.CommonDataKinds.Phone.NUMBER
                };
                arr[i] = id + " , 姓名：" + name;

                //根据联系人的ID获取此人的电话号码
                Cursor phonesCusor = getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        phoneProjection,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,
                        null,
                        null);

                //因为每个联系人可能有多个电话号码，所以需要遍历
                if (phonesCusor != null && phonesCusor.moveToFirst()) {
                    do {
                        String num = phonesCusor.getString(0);
                        arr[i] += " , 电话号码：" + num;
                    } while (phonesCusor.moveToNext());
                }
                i++;
            } while (cursor.moveToNext());
        }
        return arr;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    readContacts();
                } else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }


}
